const CONFIG_STORAGE_KEY = 'screenshotConfig';

async function initConfig() {
  return new Promise((resolve, reject) => {
    try {
      chrome.storage.local.get([CONFIG_STORAGE_KEY], result => {
        resolve(result[CONFIG_STORAGE_KEY] || {
          selectedColumns: [],
          columnIndices: {}
        });
      });
    } catch (error) {
      console.error("Storage access error:", error);
      resolve({
        selectedColumns: [],
        columnIndices: {}
      });
    }
  });
}

async function getCurrentTabHeaders() {
  return new Promise((resolve) => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (!tabs.length) return resolve({ headers: [], indices: {} });

      chrome.tabs.sendMessage(
          tabs[0].id,
          { action: 'getTableHeaders' },
          (response) => {
            if (chrome.runtime.lastError) {
              console.error('Error getting headers:', chrome.runtime.lastError);
              resolve({ headers: [], indices: {} });
            } else {
              resolve({
                headers: response?.headers || [],
                indices: response?.indices || {}
              });
            }
          }
      );
    });
  });
}

async function renderColumnSelector() {
  const container = document.getElementById('columnsContainer');
  const config = await initConfig();
  const { headers, indices } = await getCurrentTabHeaders();

  // 如果没有获取到表头，显示提示信息
  if (headers.length === 0) {
    container.innerHTML = `
      <div class="no-headers-message">
        <p>⚠️ 无法检测到表格表头</p>
        <p>请确保在表格页面打开此面板</p>
      </div>
    `;
    return;
  }

  // 按原始序号排序显示
  const sortedHeaders = [...headers].sort((a, b) => {
    return indices[a] - indices[b];
  });

  // 渲染表头选择器（按原始序号排序）
  container.innerHTML = sortedHeaders.map(column => {
    const index = indices[column];
    return `
      <div class="column-item">
        <input 
          type="checkbox" 
          id="col-${column}" 
          value="${column}"
          data-index="${index}"
          ${config.selectedColumns.includes(column) ? 'checked' : ''}
        >
        <label for="col-${column}">
          ${column} 
          <span class="column-index">(${index + 1})</span>
        </label>
      </div>
    `;
  }).join('');
}

function showToast(message, isSuccess = true) {
  const toast = document.getElementById('configToast');
  toast.textContent = message;
  toast.className = `toast show ${isSuccess ? 'success' : 'error'}`;
  setTimeout(() => toast.className = 'toast', 3000);
}

function saveConfig() {
  const checkboxes = document.querySelectorAll('#columnsContainer input[type="checkbox"]');

  const selectedColumns = [];
  const columnIndices = {};

  checkboxes.forEach(checkbox => {
    if (checkbox.checked) {
      const column = checkbox.value;
      const index = parseInt(checkbox.dataset.index);

      selectedColumns.push(column);
      columnIndices[column] = index; // 记录字段对应的原始索引
    }
  });

  // 按原始索引排序选中的列
  const sortedSelectedColumns = [...selectedColumns].sort((a, b) => {
    return columnIndices[a] - columnIndices[b];
  });

  const config = {
    selectedColumns: sortedSelectedColumns,
    columnIndices
  };

  chrome.storage.local.set({ [CONFIG_STORAGE_KEY]: config }, () => {
    if (chrome.runtime.lastError) {
      showToast('配置保存失败！', false);
      console.error('保存错误:', chrome.runtime.lastError);
    } else {
      showToast('配置保存成功！', true);
      // 输出保存结果，方便调试
      console.log('保存的配置:', {
        selectedColumns: config.selectedColumns,
        columnIndices: config.columnIndices
      });
    }
  });
}

document.addEventListener('DOMContentLoaded', async () => {
  // 显示加载状态
  document.getElementById('columnsContainer').innerHTML = '<p>正在加载表头信息...</p>';

  await renderColumnSelector();
  document.getElementById('saveConfig').addEventListener('click', saveConfig);
});